package proj

import (
	"dgo/goutils/utils"
	"flag"
	"fmt"
	"os"
	"runtime"
	"strings"
)

var (
	LOG_CONFIG_HOME         string = ""
	Cmdflag_logfile         *string
	cmdflag_logfmt          *string
	Auto_LoadConf_from_file bool = true
	app_safe_logger         *utils.SafeLogger
	CONFIG_emergency_PATH   string
)

func CmdFlagPrepareAppLogger() {
	Cmdflag_logfile = flag.String("logfile", "", "")
	cmdflag_logfmt = flag.String("logfmt", "", "")
}

func CmdFlagLogFileRepl(old, new string) {
	if Cmdflag_logfile == nil {
		return
	}

	*Cmdflag_logfile = strings.Replace(*Cmdflag_logfile, old, new, -1)
}

func WriteEmergencyMsg(fmtmsg string, args ...interface{}) {
	filename := CONFIG_emergency_PATH
	if len(filename) == 0 {
		msg := fmt.Sprintf(fmtmsg, args...)
		fmt.Fprintln(os.Stderr, msg)
		return
	}

	pid := os.Getpid() //获取进程ID

	if len(filename) > 0 && !strings.HasSuffix(filename, utils.PathSeparator) {
		filename += utils.PathSeparator
	}
	filename += fmt.Sprintf("emergency_%d_%s.log", pid, utils.TodayIDString())

	pc, _, lineno, ok := runtime.Caller(1)
	src := ""
	if ok {
		src = fmt.Sprintf("%s:%d", runtime.FuncForPC(pc).Name(), lineno)
	}

	var msg string
	if len(fmtmsg) == 0 {
		msg = fmt.Sprint(args...)
	} else if len(args) > 0 {
		msg = fmt.Sprintf(fmtmsg, args...)
	} else {
		msg = fmtmsg
	}

	msg = fmt.Sprintf("[%s] %s (%s)\r\n", utils.NowString(), msg, src)
	utils.DefaultWorkers().PostTaskFunc("WriteEmergencyMsg", func() {
		utils.AppendFile(filename, []byte(msg))
	})
}

func AppendAppLogFileWriter(logfile, log_fmt string) {
	if app_safe_logger == nil {
		app_safe_logger = utils.NewSafeLogger(1024)
		utils.SetLogger(app_safe_logger)
	}

	if len(log_fmt) == 0 {
		log_fmt = "[%D %T] [%L] %M (%s)\r\n"
	}

	flw := utils.NewLoggerTypeFileWriter(logfile)
	flw.SetMsgFormat(log_fmt)
	flw.ConfigMaxFileSize(int64(1024 * 1024 * 50))
	app_safe_logger.AddWriter(flw)
}

/**
 * file 默认不使用缓存, 如果需要使用缓存, 将cachesize 设置>0
 *   > 0后使用缓存写入
 */
func CreateAppLogger() utils.ILogger {
	if Cmdflag_logfile != nil {
		app_safe_logger = utils.NewSafeLogger(1024)
		utils.SetLogger(app_safe_logger)
		clw := utils.NewLoggerConsoleWriter()
		clw.SetMsgFormat("[%D %T] [%L] %M (%s)\r\n")
		app_safe_logger.AddWriter(clw)

		if len(*Cmdflag_logfile) > 0 {
			if len(*cmdflag_logfmt) == 0 {
				*cmdflag_logfmt = "[%D %T] [%L] %M (%s)"
			} else {
				//*cmdflag_logfmt =
				fmt.Println("logfmt:", *cmdflag_logfmt)
			}
			flw := utils.NewLoggerTypeFileWriter(*Cmdflag_logfile)
			flw.SetMsgFormat(*cmdflag_logfmt + "\r\n")
			flw.ConfigMaxFileSize(int64(1024 * 1024 * 50))
			app_safe_logger.AddWriter(flw)
		}
		return app_safe_logger
	}

	if Auto_LoadConf_from_file {
		tmpFile := utils.RootPath + string(os.PathSeparator) + "log.xml"
		if utils.FileIsExists(tmpFile) {
			app_safe_logger = utils.NewSafeLogger(1024)
			utils.SetLogger(app_safe_logger)
			SafeLoggerLoadXmlConfiguration(app_safe_logger, tmpFile)
			return app_safe_logger
		}

		tmpFile = "log.xml"
		if utils.FileIsExists(tmpFile) {
			app_safe_logger = utils.NewSafeLogger(1024)
			utils.SetLogger(app_safe_logger)
			SafeLoggerLoadXmlConfiguration(app_safe_logger, tmpFile)
			return app_safe_logger
		}
	}

	app_safe_logger = utils.NewSafeLogger(1024)
	utils.SetLogger(app_safe_logger)
	clw := utils.NewLoggerConsoleWriter()
	clw.SetMsgFormat("[%D %T] [%L] %M (%s)\r\n")
	app_safe_logger.AddWriter(clw)

	return app_safe_logger

}
